import { createStore } from 'vuex'
import user from './user';
import permission from './permission';
import route from './route';

let menus = [];
function getMenusLists(item, menu = {}) {
  item.forEach(ele => {
    if (ele.children) {
      let lists = {}
      if (ele.meta) {
        lists.name = ele.meta.title
        lists.key = ele.meta.icon
        lists.icon = ele.meta.icon
        lists.children = []
      }
      getMenusLists(ele.children, lists)
      menus.push(lists)
    } else {
      if (ele.meta) {
        if (menu.children) {
          menu.children.push({
            name: ele.meta.title,
            key: ele.meta.icon,
            icon: ele.meta.icon,
            path: ele.path
          })
        } else {
          menu.name = ele.meta.title
          menu.key = ele.meta.icon
          menu.icon = ele.meta.icon
          menu.path = ele.path
        }
      }
    }
  });
}

export default createStore({
  state: {
    counter: 0,
    menus: []
  },
  getters: {
    doubleCounter(state) {
      return state.counter * 2
    },
    roles: state => state.user.roles,
    hasRoles: state => state.user.roles && state.user.roles.length > 0,
    permission_routes: state => state.permission.routes,
    tab_routes: state => state.route.tabRoutes,
    current_route: state => state.route.currentRoute,
    permission_menus: async state => {
      const routesLists = state.permission.routes.filter(ele => !ele.hidden)
      // 递归
      getMenusLists(routesLists)
      return menus
    },
  },
  mutations: {
    add(state) {
      state.counter++
    }
  },
  actions: {
    add({ commit }) {
      setTimeout(() => {
        commit('add')
      }, 1000);
    }
  },
  modules: {
    user, permission, route
  }
})